package com.spider.service;

import com.alibaba.fastjson.JSONObject;
import com.spider.constant.JiLiUrl;
import com.spider.entity.JiliEntity;
import com.spider.entity.JiliRecord;
import com.spider.mapper.HeownsJiliMapper;
import com.spider.util.HttpTokenUtil;
import com.spider.util.JiLiUtil;
import com.spider.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 基理科技
 */
@Service
public class JiLiServiceImpl implements JiLiService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    HeownsJiliMapper mapper;
    @Autowired
    private JiliUtilService utilService;

    private final Logger logger = LoggerFactory.getLogger(JiLiServiceImpl.class);

    public static void main(String[] args) {
        String result="{\n" +
                "    \"content\": {\n" +
                "        \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpcCI6IjExMS4zMy4yMDUuMTMwIiwiY2lkIjoiMjk5ZDQ4NzM1YTU2MGE4NDE0OTdkYmQzMDhhZmExYjMiLCJ2aWQiOiI4MTciLCJpYXQiOjE2NjQ0MjEzNTUsImV4cCI6MTY2NDQyNDk1NX0=.c9692cfad56351752ca7fd4f48a674a33be6c28acc09f1df15099393806c90a4\",\n" +
                "        \"expires_in\": \"3600\"\n" +
                "    }\n" +
                "}";
        String res=StringUtil.unicodeDecode(result.toString());
        JSONObject jb=JSONObject.parseObject(res);
        JSONObject content= (JSONObject) jb.get("content");
        res= (String) content.get("access_token");
        System.out.println(res);
    }

    /**
     * 获取token
     */
    @Override
    public String getToken(){
        String token= utilService.createToken();
        System.out.println(token);
        return token;
    }


    /**
     * 价格修改
     * @param  num 默认为空，如果不为空则只跑一次
     */
    @Override
    public void priceUpdate(String num){
        //拼接参数
        String url= JiLiUrl.PRODUCT_URL+JiLiUrl.ASYNC_TASK;
        String token = this.getToken();
        System.out.println(token);
        //查询结果集
        List<JiliEntity> list = mapper.selectByDate();
        if(list.isEmpty()){
            logger.info("基理科技价格推送无数据，推送结束");
        }else{
            logger.info("基理科技价格推送查询结果集数量为"+list.size());
                try{
                    JSONObject body= JiLiUtil.getUpdatePriceBody(list);
                    if(body==null){
                        logger.info("实体拼接数据失败缺乏数据，跳过此数据:");
                    }
                    String res= HttpTokenUtil.postRequest(token,url,body);
                    System.out.println(res);
                    JiliRecord record=new JiliRecord();
                    record.setResult(res);
                    JSONObject jb=JSONObject.parseObject(res);
                    JSONObject content= (JSONObject) jb.get("content");
                    String taskId= (String) content.get("task_id");
                    record.setTaskId(taskId);
                    record.setType("修改价格");
                    record.setStatus("初始化");
                    String hs="";
                    for(JiliEntity entity:list){
                        hs=entity.getHuohao()+",";
                        mapper.updateJiliPrice(entity);
                    }
                    record.setParams(hs);
                    mapper.saveRecord(record);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("基理科技价格推送失败，失败原因："+e.getMessage());
                }
            }

    }
    /**
     * 库存新增
     * @param num 不为空则只推送一条
     */
    @Override
    public void stockInsert(String num){
        //拼接参数
        String url= JiLiUrl.PRODUCT_URL+JiLiUrl.ASYNC_TASK;
        String token = this.getToken();
        System.out.println(token);
        //拼接body
        List<JiliEntity> list = mapper.selectJiliInsert();
/*        List<JiliEntity> list=new ArrayList<JiliEntity>();
        JiliEntity en=new JiliEntity();
        en.setBrand("希恩思");
        en.setPrice(new BigDecimal(998));
        en.setHs("M-57801+0.25g");
        en.setNum("250");
        en.setUnit("mg");
        en.setJibenNum("0.25");
        en.setJibenunit("g");
        en.setChucuntiaojian("常温");
        en.setYunshufangshi("常温");
        en.setCas("1684393-77-8");
        en.setName("MHI-C16");
        en.setKc("22");
        en.setFenzishi("C62H96BrClN2");
        en.setFenziliang("982.64");
        list.add(en);*/
        if(list.isEmpty()){
            logger.info("基理科技新产品库存推送无数据，推送结束");
        }else{
            logger.info("基理科技新产品库存推送查询结果集数量为"+list.size());
            try{
                JSONObject body= JiLiUtil.insertProduceBody(list);
                if(body==null){
                    logger.info("实体拼接数据失败缺乏数据，跳过此数据");
                }
                System.out.println(body.toString());
                String res=HttpTokenUtil.postRequest(token,url,body);
                System.out.println(res);
                JiliRecord record=new JiliRecord();
                record.setParams(body.toString());
                record.setResult(res);
                JSONObject jb=JSONObject.parseObject(res);
                JSONObject content= (JSONObject) jb.get("content");
                String taskId= (String) content.get("task_id");
                record.setTaskId(taskId);
                record.setType("新增库存");
                record.setStatus("初始化");
                String hs="";
                for(JiliEntity entity:list){
                    hs=entity.getHuohao()+",";
                    mapper.saveJiliInsert(entity);
                }
                record.setParams(hs);
                mapper.saveRecord(record);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("基理科技新产品库存推送失败，失败原因："+e.getMessage());
            }
        }
    }
    /**
     * 删除产品
     * @param num 不为空则只推送一条
     */
    @Override
    public void deleteProduct(String num){
        //拼接参数
        String url= JiLiUrl.PRODUCT_URL+JiLiUrl.ASYNC_TASK;
        String token = this.getToken();
        System.out.println(token);
        //拼接body
        List<JiliEntity> list = mapper.selectJiliDelete();
/*        List<JiliEntity> list=new ArrayList<JiliEntity>();
        JiliEntity en=new JiliEntity();
        en.setBrand("希恩思");
        en.setPrice(new BigDecimal(998));
        en.setHs("M-57801+0.25g");
        en.setNum("250");
        en.setUnit("mg");
        en.setCas("1684393-77-8");
        en.setName("MHI-C16");
        list.add(en);*/
        if(list.isEmpty()){
            logger.info("基理科技下架产品推送无数据，推送结束");
        }else{
            logger.info("基理科技下架产品推送查询结果集数量为"+list.size());
            try{
                JSONObject body= JiLiUtil.deleteProductBody(list);
                if(body==null){
                    logger.info("实体拼接数据失败缺乏数据，跳过此数据");
                }
                System.out.println(body.toString());
                String res=HttpTokenUtil.postRequest(token,url,body);
                System.out.println(res);
                System.out.println(body.toString());
                JiliRecord record=new JiliRecord();
                record.setParams(body.toString());
                record.setResult(res);
                JSONObject jb=JSONObject.parseObject(res);
                JSONObject content= (JSONObject) jb.get("content");
                String taskId= (String) content.get("task_id");
                record.setTaskId(taskId);
                record.setType("下架产品");
                record.setStatus("初始化");
                String hs="";
                for(JiliEntity entity:list){
                    hs=entity.getHuohao()+",";
                    mapper.deleteJiliProduct(entity);
                }
                record.setParams(hs);
                mapper.saveRecord(record);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("基理科技下架产品推送失败，失败原因："+e.getMessage());
            }
        }

    }


    /**
     * 查看任务处理进度
     * @param num 不为空则只推送一条
     */
    @Override
    public void getTaskResult(String num){
        //拼接参数
        String url= JiLiUrl.PRODUCT_URL+JiLiUrl.ASYNC_TASK;
        String token = this.getToken();
        System.out.println(token);
        //拼接body
        List<JiliRecord> list = mapper.selectRecord();
/*        List<JiliRecord> list=new ArrayList<JiliRecord>();
        JiliRecord record=new JiliRecord();
        record.setTaskId("aacdfjec-batch-edit-spu");
        record.setStatus("初始化");
        list.add(record);*/
        if(list.isEmpty()){
            logger.info("基理科技同步结果，获取结束");
        }else{
            logger.info("基理科技同步结果查询结果集数量为"+list.size());
            for(JiliRecord task:list){
                try{
                    String resuUrl=url+"/"+task.getTaskId();
                    JSONObject body=new JSONObject(new LinkedHashMap());
                    body.put("1","1");
                    String res=HttpTokenUtil.getRequest(token,resuUrl,body);
                    System.out.println(res);
                    JSONObject jb=JSONObject.parseObject(res);
                    JSONObject content= (JSONObject) jb.get("content");
                    String status= (String) content.get("status");
                    task.setStatus(status);
                    task.setResult(res);
                    mapper.updateRecord(task);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("查看任务处理进度失败，失败原因："+e.getMessage());
                }
                //if(num!=null)break;
            }
        }
    }

}
